<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>canvas</title>
    <style>
      body {
        position: relative;
        margin: 0;
        padding: 0;
      }

      canvas {
        position: absolute;
        left: 0;
        top: 0;
      }
    </style>
  </head>

  <body>
    <!-- 注意：canvas大小要和图片宽高要一样大 -->
    <canvas id="canvas" width="480" height="610"> 你的浏览器太low了~ </canvas>
    <script>
      // 水平滚动重点：save和restore方法
      window.onload = function () {
        var canvas = document.getElementById("canvas")
        var y = 0
        if (canvas.getContext) {
          function bgMove() {
            cvsCtx.save()

            cvsCtx.clearRect(0, 0, canvas.width, canvas.height) // 清除上一次绘制的图像

            cvsCtx.translate(0, y)

            cvsCtx.drawImage(img, 0, 0)
            cvsCtx.drawImage(img, 0, canvas.height * -1) // 画两张图，无缝连接

            // 判断y偏移量
            y++
            if (y >= canvas.height) {
              y = 0
            }

            cvsCtx.restore() // 取出栈内保存的原来图片状态信息
            window.requestAnimationFrame(bgMove)
          }

          var cvsCtx = canvas.getContext("2d")

          var img = new Image()
          img.src = "./images/game/bg.jpg"
          img.onload = function () {
            bgMove()
          }
        } else {
          alert("你的浏览器太low了~")
        }
      }
    </script>
  </body>
</html>
